package org.sky.security.support;

import org.apache.logging.log4j.Logger;
import org.sky.util.JsonUtils;
import org.sky.util.LogUtils;
import org.sky.util.result.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @author weifx
 * @Title: LoginSuccessHandler
 * @ProjectName springboot-platform
 * @Description: TODO{登录成功后处理}
 * @date 2019/2/28 11:33
 * @Version 1.0
 */
public class CustomAuthenticationSuccessHandle extends SavedRequestAwareAuthenticationSuccessHandler {
    Logger logger  = LogUtils.getLogger(CustomAuthenticationSuccessHandle.class);
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException,ServletException {
        //获得授权后可得到用户信息   可使用SUserService进行数据库操作
        SecurityUser userDetails = (SecurityUser)authentication.getPrincipal();
        userDetails.setLoginDate(new Date());
        userDetails.setLoginIp(getIpAddress(request));
        //输出登录提示信息
        logger.info("用户{}登录成功,登录IP{}",userDetails.getCode(),getIpAddress(request));
        super.onAuthenticationSuccess(request, response, authentication);
    }

    public String getIpAddress(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
